package com.fary.validator;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CustomerValidator implements ConstraintValidator<CustomerValid, Object> {

    private List<String> clientTypes = new ArrayList<>();

    String customerType = "";

    String overseas = "";

    String documentType = "";

    String identityNumber = "";

    public void initialize(CustomerValid constraintAnnotation) {
        clientTypes = Arrays.asList(constraintAnnotation.clientType());
        customerType = constraintAnnotation.customerType();
        overseas = constraintAnnotation.overseas();
        documentType = constraintAnnotation.documentType();
        identityNumber = constraintAnnotation.identityNumber();
    }


    public boolean isValid(Object value, ConstraintValidatorContext constraintContext) {
        String error = "";
        for (String clientType : clientTypes) {
            String customerTypeValue = (String) ReflectUtil.getFieldValue(value, clientType + StrUtil.upperFirst(customerType));
            String overseasValue = (String) ReflectUtil.getFieldValue(value, clientType + StrUtil.upperFirst(overseas));
            String documentTypeValue = (String) ReflectUtil.getFieldValue(value, clientType + StrUtil.upperFirst(documentType));
            String identityNumberValue = (String) ReflectUtil.getFieldValue(value, clientType + StrUtil.upperFirst(identityNumber));
            if (StrUtil.isBlank(customerTypeValue)) {
                error = clientType + "客户类型不能为空！";
                break;
            }
            if (StrUtil.isBlank(overseasValue)) {
                error = clientType + "是否境外不能为空！";
                break;
            }
            if (StrUtil.isBlank(documentTypeValue)) {
                error = clientType + "证件类型不能为空！";
                break;
            }
            if (StrUtil.isBlank(identityNumberValue)) {
                error = clientType + "证件号码不能为空！";
                break;
            }
        }

        if (!StrUtil.isBlank(error)) {
            constraintContext.disableDefaultConstraintViolation();
            constraintContext.buildConstraintViolationWithTemplate(error).addConstraintViolation();
            return false;
        }
        return true;
    }


}